import { useEffect, useState } from 'react'
import store from './store'

export default function App() {
  const [show, setShow] = useState(true)
  return (
    <div>
      <h1>Redux基础</h1>
      <button onClick={() => setShow(!show)}>点击切换挂载/卸载组件</button>
      {show ? <Son /> : null}
    </div>
  )
}

function Son() {
  // 把仓库的 count 作为组件状态的初始值
  const [count, setCount] = useState(store.getState().count)

  useEffect(() => {
    // 组件挂载时，订阅(监听)仓库变化
    const unSubscribe = store.subscribe(function () {
      // 仓库发生变化干点什么，把 count 同步到组件状态上(更新UI)
      setCount(store.getState().count)
    })
    // 组件卸载时，取消订阅(监听)
    return () => {
      unSubscribe()
    }
  }, [])

  return (
    <div>
      <h2>子组件</h2>
      <h2>count:{count}</h2>
      {/* 仓库数据修改需要通过 dispatch() 修改 */}
      <button onClick={() => store.dispatch({ type: 'add' })}>+1</button>
      <button onClick={() => store.dispatch({ type: 'minus' })}>-1</button>
    </div>
  )
}
